package com.ruihang.generalibrary.ui.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.ruihang.generalibrary.R;

/**
 * Created by Ly on 2016/11/3.
 */
public class CustomRelativeLayout extends RelativeLayout {

    protected OnSizeChangeListener sizeChangeListener;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CustomRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public CustomRelativeLayout(Context context) {
        super(context);
    }

    public CustomRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initCustomAttr(context,attrs,0);
    }

    public CustomRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCustomAttr(context,attrs,defStyleAttr);
    }

    private void initCustomAttr(Context context, AttributeSet attrs, int defStyle){
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomRelativeLayout, defStyle, 0);
        String sizeChange=a.getString(R.styleable.CustomRelativeLayout_sizeChangeListener);
        if(!TextUtils.isEmpty(sizeChange)){
            try {
                Class c= Class.forName(sizeChange);
                if(c!=null){
                    Object o=c.newInstance();
                    if(o instanceof OnSizeChangeListener){
                        setSizeChangeListener((OnSizeChangeListener) o);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        a.recycle();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if(sizeChangeListener!=null){
            sizeChangeListener.onSizeChanged(this, w, h, oldw, oldh);
        }
    }

    public OnSizeChangeListener getSizeChangeListener() {
        return sizeChangeListener;
    }

    public CustomRelativeLayout setSizeChangeListener(OnSizeChangeListener sizeChangeListener) {
        this.sizeChangeListener = sizeChangeListener;
        return this;
    }
}
